package com.example.demo.cdesign.web;

import com.example.demo.common.entity.User;
import com.example.demo.common.security.Cryptos;
import com.example.demo.common.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Resource
    private UserService userService;

    @RequestMapping(value = "login")
    public ModelAndView loginPage(ModelAndView modelAndView) {
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @RequestMapping(value = "/user/logout")
    public ModelAndView logout(ModelAndView modelAndView, HttpSession session) {
        session.removeAttribute("loginUser");
        modelAndView.setViewName("login");
        return modelAndView;
    }


    @PostMapping(value = "/user/login")
    public ModelAndView login(@RequestParam("username") String username,
                              @RequestParam("password") String password,
                              ModelAndView modelAndView, HttpSession session) {
        if (StringUtils.isNotEmpty(username)) {
//            User query = new User();
//            query.setLoginName(username);
//            List<User> userList = userService.find(query);
//            User user = userList.stream().findFirst().orElseGet(User::new);
            User user = new User();
            user.setPassword(Cryptos.aesEncrypt("123456"));
            if (StringUtils.equals(Cryptos.aesDecrypt(user.getPassword()), password)) {
                //登陆成功，防止表单重复提交，可以重定向到主页
                session.setAttribute("loginUser", username);
                modelAndView.setViewName("redirect:/index");
                return modelAndView;
            }
        }
        //登陆失败
        modelAndView.addObject("msg", "用户名密码错误");
        modelAndView.setViewName("login");
        return modelAndView;
    }

}
